import Phaser from "phaser";
import QGamePlugin from "./QGamePlugin";

import { QUIView } from "./QUIView";
import { QUILabel } from "./QUILabel";
import { QUIHorizontalLayout } from "./QUIHorizontalLayout";
import { QUIVerticalLayout } from "./QUIVerticalLayout";
import { QUIScrollArea } from "./QUIScrollArea";
import { QUIGridLayout } from "./QUIGridLayout";
import { QUIButton } from "./QUIButton";
import { QUIInput } from "./QUIInput";
import { QUIComboBox } from "./QUIComboBox";

export default class QGameInstantiateObject {
    private scene: Phaser.Scene;
    private manger: QGamePlugin;
    constructor(scene: Phaser.Scene, manger: QGamePlugin) {
        this.scene = scene;
        this.manger = manger;
    }

    parse(xmlString: string): QUIView | null {
        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(xmlString, "text/xml");
        const rootNode = xmlDoc.documentElement;
        const view = this.parseNode(rootNode);
        if (view) {
            view.forcedLayout();
        }
        return view;
    }

    // private relayout(view: QUIView) {
    //     if (view) {
    //         view.layout();
    //         view.children.forEach((child) => {
    //             this.relayout(child);
    //         });
    //     }
    // }

    /**
     * 递归解析XML节点
     */
    private parseNode(node: Element): QUIView | null {
        const tagName = node.tagName.toLowerCase();
        // 解析属性
        const attributes = this.parseAttributes(node);
        let view: QUIView | null = null;

        view = this.setupView(tagName, attributes);
        if (view === null) {
            console.warn(`Unknown UI element: ${tagName}`);
            return null;
        }
        // 递归处理子节点
        Array.from(node.children).forEach((childNode) => {
            const childView = this.parseNode(childNode);
            if (childView === null) return;
            view.add(childView);
        });

        return view;
    }

    // 以下是各种UI元素的设置方法
    private setupView(tagName: string, attrs: any): QUIView | null {
        if (this.manger.add === null) return null;
        let o: QUIView | null = null;
        switch (tagName) {
            case "QUIView":
            case "quiview":
            case "view":
                o = new QUIView(this.scene, this.manger, attrs);
                this.manger.add.pushNode(o);
                return o;
            case "QUILabel":
            case "quilabel":
            case "label":
                o = new QUILabel(this.scene, this.manger, attrs);
                this.manger.add.pushNode(o);
                return o;
            case "QUIButton":
            case "quibutton":
            case "button":
                o = new QUIButton(this.scene, this.manger, attrs);
                this.manger.add.pushNode(o);
                return o;
            case "QUIInput":
            case "quiinput":
            case "input":
                o = new QUIInput(this.scene, this.manger, attrs);
                this.manger.add.pushNode(o);
                return o;
            case "QUIComboBox":
            case "quicombobox":
            case "combobox":
                o = new QUIComboBox(this.scene, this.manger, attrs);
                this.manger.add.pushNode(o);
                return o;

            case "QUIVerticalLayout":
            case "quiverticallayout":
            case "vertical":
                o = new QUIVerticalLayout(this.scene, this.manger, attrs);
                this.manger.add.pushNode(o);
                return o;
            case "QUIHorizontalLayout":
            case "quihorizontallayout":
            case "horizontal":
                o = new QUIHorizontalLayout(this.scene, this.manger, attrs);
                this.manger.add.pushNode(o);
                return o;
            case "QUIGridLayout":
            case "quigridlayout":
            case "grid":
                o = new QUIGridLayout(this.scene, this.manger, attrs);
                this.manger.add.pushNode(o);
                return o;
            case "QUIScrollArea":
            case "quiscrollarea":
            case "scroll":
                o = new QUIScrollArea(this.scene, this.manger, attrs);
                this.manger.add.pushNode(o);
                return o;
        }
        return null;
    }
    /**
     * 解析节点属性
     */
    private parseAttributes(node: Element): Record<string, any> {
        const attributes: Record<string, any> = {};

        Array.from(node.attributes).forEach((attr) => {
            let value = this.parseAttributeValue(attr.value);
            let key = attr.name;
            switch (attr.name) {
                case "widthratio":
                    key = "widthRatio";
                    break;
                case "heightratio":
                    key = "heightRatio";
                    break;
                case "miniwidth":
                    key = "miniWidth";
                    break;
                case "miniheight":
                    key = "miniHeight";
                    break;
                // case "maxwidth":
                //     key = "maxWidth";
                //     break;
                // case "maxheight":
                //     key = "maxHeight";
                //     break;
                case "borderwidth":
                    key = "borderWidth";
                    break;
                case "bordercolor":
                    key = "borderColor";
                    break;
                case "backgroundcolor":
                    key = "backgroundColor";
                    break;
                case "alignx":
                    key = "alignX";
                    break;
                case "aligny":
                    key = "alignY";
                    break;
                case "paddingtop":
                    key = "paddingTop";
                    break;
                case "paddingbottom":
                    key = "paddingBottom";
                    break;
                case "paddingleft":
                    key = "paddingLeft";
                    break;
                case "paddingright":
                    key = "paddingRight";
                    break;
                case "imageurl":
                    key = "imageUrl";
                    break;
                case "text":
                    key = "text";
                    break;
                case "fontsize":
                    key = "fontSize";
                    break;
                case "fontcolor":
                    key = "fontColor";
                    break;
                case "fontfamily":
                    key = "fontFamily";
                    break;
                case "placeholder":
                    key = "placeholder";
                    break;
                case "inputtype":
                    key = "inputType";
                    break;
            }
            // if (key == "maxwidth" || key == "maxheight") {
            //     key = key.replace("width", "Width");
            //     key = key.replace("height", "Height");
            //     value = parseInt(value);
            // }
            attributes[key] = value;
        });

        return attributes;
    }
    /**
     * 转换属性值
     */
    private parseAttributeValue(value: string): any {
        // 尝试解析为数字
        if (!isNaN(Number(value))) return Number(value);

        // 尝试解析为布尔值
        if (value.toLowerCase() === "true") return true;
        if (value.toLowerCase() === "false") return false;

        // 尝试解析为JSON
        try {
            return JSON.parse(value);
        } catch (e) {
            return value;
        }
    }
}
